//适配umi hooks page data
import React, {useContext, useEffect, useRef, useState} from "react"
import {Form, Input} from "antd"
import "./table-hooks.less"
import CheckOutlined from "@ant-design/icons/lib/icons/CheckOutlined"
import EditOutlined from "@ant-design/icons/lib/icons/EditOutlined"
import CloseOutlined from "@ant-design/icons/es/icons/CloseOutlined"

const formatResult = (page) => ({
	list: page.pageData,
	total: page.total
})

/*
 * initData 初始被选中的数据列表
 * rowKey 选中数据中关键属性,一般指id,用于提交数据时获取主键值
 * */
const useTableCheck = ({initData, rowKey="id"}) => {
	const [checkItems, setCheckItems] = useState(initData || [])
	return ({
		//真接用表格rowSelection属性
		rowSelection: {
			onChange: (rowKeys, ...params) => {
				setCheckItems(rowKeys)
			},
			onSelect: (record, selected, selectedRows,...other) => {
				if(selected) {
					setCheckItems([...new Set([].concat(checkItems).concat(record[rowKey]))])
				} else {
					setCheckItems(checkItems.filter(item => item !== record[rowKey]))
				}
			},
			selectedRowKeys: checkItems,
			fixed: true
		},
		//可获取选中的数据库
		items: checkItems,
		//可获取被选中的关键属性列表
		ids: (checkItems || []).map(item => item[rowKey || 'id'])
	})
}


const useTableCellEditContext = ({rowKey, setRowKey}) => {
	const context = React.createContext({
		rowKey,
		setRowKey
	})
	return {
		TableCellEditContext: context
	}
}

const EditableContext = React.createContext()

/*
* 用于构建编辑单元格
* @param editingIndex 当前正编辑的行,一般从context中获取
* @param setEditingIndex 设置当前正编辑的行,一般从context中获取
*
* 需要在希望编辑的列设置onCell
* onCell: (record, rowIndex) => ({
			record,
			editable: true,
			dataIndex: 'name',
			rowIndex,
			title: '名称',
			handleSave: (data) => {
				updateName(data)
			}
		})
* */
const useTableCellEdit = ({editingIndex, setEditingIndex, cellForm}) => {


	const EditableRow = ({index, ...props}) => {
		return (
			<tr {...props} />
		)
	}

	const EditableCell = ({editable, title, children, dataIndex, record, rowIndex, handleSave, ...restProps}) => {
		//是否在编辑状态
		const [form] = Form.useForm()

		const toggle = () => {
			setEditingIndex(rowIndex === editingIndex ? null : rowIndex)
		}

		const save = async e => {
			try {
				const values = await form.validateFields()
				await handleSave({...record, ...values})
				toggle()
			} catch (errInfo) {
			}
		}

		if (!editable) {
			return <td {...restProps}>{children}</td>
		}

		if (editingIndex === rowIndex) {
			return <td {...restProps} className="zr-editable-cell-value-wrap">
				<div>
					{cellForm
						? cellForm
						: <Form form={form} component={false} initialValues={{name: record[dataIndex]}}>
							<Form.Item name={dataIndex} 
								validateFirst={true}
								rules={[{
								required: true,
								message: `${title}必须填写`,
							}]}>
								<Input onPressEnter={save}/>
							</Form.Item>
							<CheckOutlined onClick={save}/>
							<CloseOutlined onClick={() => setEditingIndex(null)}/>
						</Form>
					}
				</div>
			</td>
		} else {
			return <td {...restProps} className="zr-editable-cell-value-wrap">
				<div onDoubleClick={toggle}>
					<div className={'read-only'}>{children}</div>
					<EditOutlined className={'text-cell'} onClick={toggle}/>
				</div>
			</td>
		}
	}

	const components = {
		body: {
			row: EditableRow,
			cell: EditableCell,
		}
	}

	//返回components作为Table组件的components属性
	return {
		components
	}
}

export {formatResult, useTableCheck, useTableCellEdit, useTableCellEditContext}